<!--
  - Copyright (c) 2021.  北京维数科技有限公司
  - Date :  2021/3/25
  - Author ：F12 Console=> atob("MzMxNDkxODAwQHFxLmNvbQ==")
  - Version ：1.0.0
  -->

<template>
  <el-form ref="form" :model="FormData" label-width="80px" style="background-color: #fff;flex: 1">
    <el-form-item label="请求地址">
      <el-input v-model="FormData.URL"/>
    </el-form-item>
    <el-form-item label="请求类型">
      <el-select v-model="FormData.Type" placeholder="请选择请求类型" value="">
        <el-option label="GET" value="GET"/>
        <el-option label="POST" value="POST"/>
        <el-option label="PUT" value="PUT"/>
        <el-option label="DELETE" value="DELETE"/>
      </el-select>
    </el-form-item>
    <el-form-item label="请求头">
      <el-input type="textarea" v-model="FormData.Header"/>
    </el-form-item>
    <el-form-item label="请求内容">
      <el-input type="textarea" v-model="FormData.Body"/>
    </el-form-item>
    <el-form-item label="请求结果">
      <el-input type="textarea" readonly :value="Result"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">测试</el-button>
      <el-button>取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
    import $http from '@/utils/request'
    export default {
    name: 'APITest',
    data () {
      return {
        FormData: {
          URL: '',
          Type: 'POST',
          Header: '{}',
          Body: '{}'
        },
        Result: ''
      }
    },
    methods: {
      async onSubmit () {
        let Options = {
          cache: 'no-cache',
          method: this.FormData.Type,
          referrer: 'no-referrer',
          header: this.FormData.Header
        }
        let Body = JSON.parse(this.FormData.Body)
        if (this.FormData.Type === 'POST') {
          this.Result = JSON.stringify(await $http.post(this.FormData.URL, Body))
          // console.log(request)
        }else if (this.FormData.Type === 'PUT') {
          this.Result = JSON.stringify(await $http.put(this.FormData.URL, Body))
        }else if(this.FormData.Type === 'DELETE'){
          let Param = '?'
          for (let k in Body) {
            Param += `${k}=${Body[k]}&`
          }
          this.Result = JSON.stringify(await $http.delete(this.FormData.URL + Param))
        } 
        else {
          let Param = '?'
          for (let k in Body) {
            Param += `${k}=${Body[k]}&`
          }
          this.Result = JSON.stringify(await $http.get(this.FormData.URL + Param))
        }
      }
    }
  }
</script>
